<?php
/**
 * Created by PhpStorm.
 * User: 马萍
 * Date: 2017/11/22
 * Time: 22:23
 */

namespace Admin\Logic;

use Admin\Logic\StockLogic;
use Admin\Logic\FoodLogic;

class OrderLogic
{
    /**
     * 获取订单数据
     * @param int $id
     * @return bool|mixed
     */
    public static function getAll()
    {
        try{
            $order = D('Order');
            $data = $order
                ->where('is_del=0')
                ->field('*')
                ->select();
            return $data;
        }catch (\Exception $e){
            return false;
        }

    }

    /**
     * 执行添加库存操作
     * @param $data
     * @return bool
     */
    public static function create($params)
    {
        try {
            $model = M();
            $model->startTrans();
            $food_arr = $params['food_id'];
            unset($params['food_id']);
            $flag = true;
            $order = D('Order')->data($params)->add();
            if ($order === false) {
                $flag = false;
            }

            //组装订单详情表数据
            if (!empty($food_arr)) {
                $order_detail_arr = [];
                foreach ($food_arr as $k => $v) {
                    $order_detail_arr[$k]['order_id'] = $params['order_id'];
                    $order_detail_arr[$k]['food_id'] = $v;
                }
                $order_detail = D('OrderDetail')->data($order_detail_arr)->add();
                if ($order_detail === false) {
                    $flag = false;
                }
            }
            //判断是否支付成功，成功则处理库存
            if ($params['is_pay'] == '已支付') {
                //获取菜谱用了多少材料
                $food = FoodLogic::getFindAll($food_arr);
                //更新库存明细表
                $stock_detail = StockLogic::updateDetailOrder($food, $params['order_id']);

                if ($stock_detail === false) {
                    $flag = false;
                }
            }

            if ($flag) {
                $model->commit();
                return true;
            } else {
                $model->rollback();
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }


    public static function delete($id){
        try {
            $update = D('Order')->save(['id'=>$id,'is_del'=>1]);
            return json_encode(['code'=>1]);
        } catch (\Exception $e) {
            return json_encode(['code'=>0,'errorMsg'=>'删除失败，请重试']);
        }
    }

    public static function getOne($id){
        $order = D('Order')->where('id='.$id)->find();
        $foods = D('OrderDetail') ->where('order_id='.$order['order_id'])->select(['food_id','num']);
        $food_id = array();
        foreach ($foods as $item){
            array_push($food_id,$item['food_id']);
        }
        $order['food_id'] = $food_id;
        return $order;
    }

    /**
     * 根据订单id（1维数组）查询所有菜谱id
     * @param array $order
     * @return array
     */
    public static function getFoodByOrderIds(array $order)
    {
        $food = D('OrderDetail as d')
            ->where(['order_id'=>['in',$order]])
            ->join('left join food_food as f on f.id=d.food_id')
            ->field(['d.food_id','d.spec','f.loss'])
            ->select();

        return $food;
    }

    /**
     * 获取订单表中 reserve_time 的最大值的时间戳
     * @return bool|false|int
     */
    public static function getMaxTime()
    {
        try{
            $date = D('Order')
                ->field('max(reserve_time) as max_time')
                ->find();

            return  strtotime($date['max_time']);
        } catch (\Exception $e){
            return false;
        }
    }


    /**
     * 查询订单根据时间分组
     * @param $nowTime
     * @param $startTime
     * @return bool
     */
    public static function getOrderGroupTime($nowTime,$startTime)
    {
        try{

            $dayData = D('Order')
                ->where(['reserve_time'=>['BETWEEN',[$nowTime,$startTime]]])
                ->group('DATE_FORMAT(reserve_time,"%Y-%m-%d")')
                ->field("DATE_FORMAT(reserve_time,'%Y-%m-%d') as 时间, sum(order_total) as 订单金额, count(*) as 订单总数")
                ->select();

            return $dayData;
        } catch (\Exception $e){
            return false;
        }
    }


    /**
     * 获取某一天的订单详情信息
     * @param $date
     * @return bool|mixed
     */
    public static function getDayOrderDetail($date)
    {
        try{

            $order_food = D('Order as o')
//                ->where(['o.reserve_time'=>['gt',$date.' 00:00:00'],])
//                ->where(['o.reserve_time'=>['lt',$date.' 23:59:59']])
                ->where(['o.reserve_time'=>['BETWEEN',[$date.' 00:00:00',$date.' 23:59:59']]])
                ->join('left join food_order_detail as d on o.id=d.order_id')
                ->join('left join food_food as f on d.food_id=f.id')
                ->field('d.food_id,d.spec,f.loss,d.num')
                ->select();

            return $order_food;

        } catch (\Exception $e){
            return false;
        }

    }





}